package com.csu.geo.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.csu.geo.entity.AdminUser;
import com.csu.geo.service.AdminUserService;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Handles requests for the application home page.
 */
@Controller
public class AdminUserController {
	
	private static final Logger logger = LoggerFactory.getLogger(AdminUserController.class);
	
	@Autowired
	private AdminUserService adminUserService;
	
	@RequestMapping(value="/back")
	public  ModelAndView back()
	{
		ModelAndView view=new ModelAndView("backLogin");
		logger.info("后台首页启动！");
		return view;
	}
	
	/**
	 * 保存新建的管理员或者审核员
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	@RequestMapping(value="/backsaveadminuser")
	public void backSaveAdminuser(HttpServletRequest request,HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException
	{
		String data =new String(request.getParameter("data").getBytes("iso-8859-1"), "utf-8");
		ObjectMapper mapper=new ObjectMapper();
		@SuppressWarnings("unchecked")
		Map<String, String> map=mapper.readValue(data, Map.class); 
		AdminUser adminUser=new AdminUser();
		adminUser.setUserName(map.get("userName"));
		adminUser.setEmail(map.get("email"));
		adminUser.setAuthority(Integer.parseInt(map.get("authority")));
		adminUser.setPassword(map.get("passWord"));
		adminUser.setTel(map.get("tel"));
		DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		  String time=format.format(new Date());
		  adminUser.setCreateTime(time);
		  adminUser.setAcademic(map.get("academic"));
		  adminUser.setProfessional(map.get("professional"));
		  if(adminUserService.getAdminUser(map.get("userName"))!=null)
		  {
			response.getWriter().println("用户名已存在！");
		  }
		  else {
			  int flag=adminUserService.saveAdminUser(adminUser);
			  ModelAndView view=new ModelAndView();
				if(flag!=0)
				{
					String result="{\"msg\":\"0\"}";
					response.getWriter().println(result);// 成功
					
				}else {
					String result="{\"msg\":\"1\"}";
					response.getWriter().println(result);// 失败
				}
		}
		
	}
	
	@RequestMapping(value="/backlogin")
	public ModelAndView backLogin(HttpSession session,HttpServletRequest request,HttpServletResponse response)
	{
		String name=request.getParameter("username");
		String password=request.getParameter("password");
		String result=adminUserService.backLogin(name, password);
		if(result.equals("0000"))
		{
			session.setAttribute("adminuser",name);
			ModelAndView view=new ModelAndView("backhome");
			view.addObject("adminuser",name);
			logger.info("----------------后台用户登陆成功！！------------------------------");
			return view;
		}
		else if(result.equals("0002"))
		{
			ModelAndView view=new ModelAndView("backlogin");
			view.addObject("msg", "您的不是管理员账号，请联系管理员！");
			return view;
		}
		else {
			ModelAndView view=new ModelAndView("backlogin");
			logger.info("----------------后台用户登陆失败！！------------------------------");
			view.addObject("msg", "用户名或密码错误！");
			return view;
		}
	}
	/**
	 * 获取所有管理员／审核员数据 1管理员 2审核员
	 * @param request
	 * @param response
	 * @throws IOException 
	 */	
	@RequestMapping(value="/getAllAdminUser")
	public void getAllAdminUser(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		List<AdminUser> result=adminUserService.getAllAdminUser();
		ObjectMapper mapper=new ObjectMapper();
		String data=new String(mapper.writeValueAsString(result).getBytes("UTF-8"),"iso-8859-1");
		logger.info("----------------获取所有审核员成功------------------------------");
		response.getWriter().println(data);
	}
	
	/**
	 * 后台获取管理员 
	 * 查询也可使用该接口 authority{0:表示全部；1:管理员；2；表示审核员} userame：all表示全部
	 * @param request
	 * @param response
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value="/backGetAdminUser")
	public void backGetTagUserInfo(HttpServletRequest request,HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException
	{
		String data =new String(request.getParameter("data").getBytes("iso-8859-1"), "utf-8");
		ObjectMapper mapper=new ObjectMapper();
		@SuppressWarnings("unchecked")
		Map<String, String> map=mapper.readValue(data, Map.class);
		String userName=map.get("userName");
		Integer authority=Integer.parseInt(map.get("authority"));
		List<AdminUser> resultList=new ArrayList<AdminUser>();
		if("all".equals(userName)&&authority==0)
		{
			resultList=adminUserService.getAllAdminUser();
		}
		else if(userName!="all"&&authority==0)
		{
			resultList=adminUserService.getAdminUserByName(userName);
		}
		else if("all".equals(userName)&&authority!=0)
		{
			resultList=adminUserService.getAdminUserByAuthority(authority);
		}
		else if(userName!="all"&&authority!=0){
			resultList=adminUserService.getAdminUserByAuthorityAndUserName(authority, userName);
		}
		ObjectMapper mapper2=new ObjectMapper();
		String  result=new String(mapper2.writeValueAsString(resultList).getBytes("UTF-8"),"iso-8859-1");
		logger.info("----------------后台审核员查询成功------------------------------");
		response.getWriter().println(result);
	}
	
	/**
	 * 后台删除管理员 0000:删除成功  1111:删除失败
	 * @param request
	 * @param response
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value="/backDeleteAdminUser")
	public void backDeleteTagUser(HttpServletRequest request,HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException
	{
		String data =new String(request.getParameter("data").getBytes("iso-8859-1"), "utf-8");
		ObjectMapper mapper=new ObjectMapper();
		@SuppressWarnings("unchecked")
		Map<String, String> map=mapper.readValue(data, Map.class);
		Integer id=Integer.parseInt(map.get("id"));
		Integer result=adminUserService.deleteAdminUser(id);
		if(result>0)
		{
			logger.info("----------------后台用户删除成功！！------------------------------");
		response.getWriter().println("0000");
		}
		else {
			logger.info("----------------后台用户删除失败！！------------------------------");
			response.getWriter().println("1111");
		}
		
	}
	/**
	 * 更新审核员权限  1 管理员  2   审核员
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	@RequestMapping(value="/backUpdateAdminUserActiveStatus")
	public void backUpdateTagUserActiveStatus(HttpServletRequest request,HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException
	{
		String data=request.getParameter("data");
		ObjectMapper mapper=new ObjectMapper();
		@SuppressWarnings("unchecked")
		Map<String, String> map=mapper.readValue(data, Map.class);
		Integer id=Integer.parseInt(map.get("id"));
		Integer authority=Integer.parseInt(map.get("authority"));
		int flag=adminUserService.updateAdminUserAuth(authority, id);
		if(flag>0)
		{
			logger.info("----------------后台用户更新成功！！------------------------------");
		response.getWriter().println("0000");
		}
		else {
			logger.info("----------------后台用户更新失败！！------------------------------");
			response.getWriter().println("1111");
		}
	}
	@RequestMapping(value="/getAdminUserInfo")
	public void  getAdminUserInfo(HttpServletRequest request,HttpServletResponse response,HttpSession session)
	{
		String adminUserStr=session.getAttribute("adminuser").toString();
		AdminUser adminUser=adminUserService.getAdminUser(adminUserStr);
		ObjectMapper mapper = new ObjectMapper();
		try {
			String  result=new String(mapper.writeValueAsString(adminUser).getBytes("UTF-8"),"iso-8859-1");
			response.getWriter().println(result);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@RequestMapping(value = "/updateAdminUserInfo")
	public void updateUserInfo(HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws IOException
	{
		String data =new String(request.getParameter("data").getBytes("iso-8859-1"), "utf-8");
		//String data=request.getParameter("data");
		ObjectMapper mapper=new ObjectMapper();
         @SuppressWarnings("unchecked")
		Map<String, String> map=mapper.readValue(data, Map.class);
		String name = session.getAttribute("adminuser").toString();
		String email =map.get("email");
		String tel = map.get("tel");
		String password = map.get("password");
		String academic=map.get("academic");
		String professional=map.get("professional");
		Integer code = adminUserService.updateAdminUser(email, tel, password, professional, academic, name);
		if (code == 1) {
			String result="{\"msg\":\"0\"}";
			response.getWriter().println(result);// 成功
			logger.info("------------审核员信息更新成功------------");
		} else {
			String result="{\"msg\":\"1\"}";
			response.getWriter().println(result);// 失败
			logger.info("------------审核员信息更新失败------------");
		}
	}
}
